package com.bee.剑指offer;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 棵二叉树不对称。树的反转必须节点都相等
 */
public class 对称的二叉树 {

    private static TreeNode empty = new TreeNode(-1);


    /**
     * 使用层次遍历放入List的数组中，将数组中其实位置和结束位置进行比较
     * ，比较的过程中如果存在不相等的情况就不是对称二叉树
     *
     * @param pRoot
     * @return
     */
    static boolean isSymmetrical(TreeNode pRoot) {
        if (pRoot == null) {
            return true;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(pRoot);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll != empty) {
                    queue.offer(poll.left == null ? empty : poll.left);
                    queue.offer(poll.right == null ? empty : poll.right);
                }
                list.add(poll.val);
            }
            // 检测每一层是否对称
            if (!check(list)) {
                return false;
            }
        }
        return true;
    }

    private static boolean check(List<Integer> list) {
        int l = 0;
        int r = list.size() - 1;
        while (l < r) {
            if (!list.get(l).equals(list.get(r))) {
                return false;
            }
            l++;
            r--;
        }
        return true;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        boolean symmetrical = isSymmetrical(root);
        System.out.println(symmetrical);
    }
}
